<template>
  <div :id="id" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import * as u from '@/util/util'

const props = defineProps({
  option: {
    type: Object,
    default: () => ({})  // 防止未传 option 时出错
  },
  id: {
    type: String,
    default: u.uuid()
  }
})

const chartInstance = ref(null)
const chartEl = ref(null)
let resizeObserver = null

const initChart = () => {
  if (!chartEl.value || !props.option || typeof props.option !== 'object') return

  chartInstance.value = markRaw(echarts.init(chartEl.value))
  chartInstance.value.setOption(props.option)

  // 使用 ResizeObserver 监听容器尺寸变化，自动调用 resize
  resizeObserver = new ResizeObserver(() => {
    chartInstance.value?.resize()
  })
  resizeObserver.observe(chartEl.value)
}

const disposeChart = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
  if (resizeObserver && chartEl.value) {
    resizeObserver.unobserve(chartEl.value)
    resizeObserver.disconnect()
    resizeObserver = null
  }
}

onMounted(() => {
  chartEl.value = document.getElementById(props.id)
  initChart()
})

// 监听 option 变化并更新图表（深度监听）
watch(() => props.option, (newOption) => {
  if (chartInstance.value && newOption && typeof newOption === 'object') {
    chartInstance.value.setOption(newOption)
  }
}, {deep: true})

onBeforeUnmount(() => {
  disposeChart()
})
</script>

<style scoped>
/* 这里根据需要写样式 */
</style>
